# 本机配置的邮件发送服务

import os

from py.storage import AppObj
from py.storage.SettingUtil import mail
from py.uitls import EmailUtil

from py.uitls.Logger import myLogger


def send_mail(mailto, title, msg='', file_name=None):
    try:
        # 标题区分指令消息（RES代表回复的消息）
        title = "RES " + AppObj.device_id + ": " + title
        # 处理换行

        if msg is None:
            msg = ''
        msg = msg.replace("\r\n\r\n", "<br/>").replace("\n", "<br/>")

        # 首先使用获得第一个邮箱的链接，失败则使用第二个邮箱的链接
        smtp = EmailUtil.get_smtp_login(mail.smtp_server, mail.smtp_port, mail.user, mail.pwd)
        send_user = mail.user
        if smtp is None:
            mail2 = mail.get_two()
            smtp = EmailUtil.get_smtp_login(mail2.smtp_server, mail2.smtp_port, mail2.user, mail2.pwd)
            send_user = mail2.user
        EmailUtil.send(smtp, send_user, mailto, title, msg, file_name)

        # 邮件发送完成后，将文件删除
        if file_name is not None:
            path = os.getcwd() + "\\" + file_name
            if os.path.exists(path):
                os.remove(path)

        return True
    except Exception as e:
        myLogger.exception(e)
        return False
